/**
 * 应用状态管理
 */
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
  checkNetwork,
  getBrowserInfo,
  getPlatformName,
  getPlatformType,
  getScreenInfo,
  getTerminalType,
  getWechatVersion,
  isWechatBrowser,
  isWechatEnvironment,
  isWechatMiniProgram,
} from '../utils/platform'

export const useAppStore = defineStore('app', () => {
  // 应用信息
  const appInfo = ref({
    name: '桃陈帝管理后台',
    version: '1.0.0',
    title: '桃陈帝管理后台',
    copyright: '桃陈帝科技有限公司',
    description: '管理后台应用',
  })

  // 平台信息
  const platformInfo = ref({
    type: getPlatformType(),
    name: getPlatformName(),
    terminal: getTerminalType(),
    os: '',
    device: null as any,
    browser: null as any,
    wechat: {
      isWechatBrowser: false,
      isWechatMiniProgram: false,
      isWechatEnvironment: false,
      version: '',
      canUseJSSDK: false,
    },
    isReady: false,
  })

  // 屏幕信息
  const screenInfo = ref(getScreenInfo())

  // 系统配置
  const systemConfig = ref({
    theme: 'light',
    language: 'zh-CN',
    networkTimeout: 10000,
    enableDebug: false,
  })

  // 全局加载状态
  const globalLoading = ref(false)
  const loadingText = ref('加载中...')

  // 计算属性
  const isH5 = computed(() =>
    platformInfo.value.type === 'h5' || platformInfo.value.type === 'h5-wechat',
  )
  const isApp = computed(() => platformInfo.value.type === 'app')
  const isMiniProgram = computed(() => platformInfo.value.type.startsWith('mp-'))
  const isWechat = computed(() => platformInfo.value.wechat.isWechatEnvironment)
  const isWechatH5 = computed(() => platformInfo.value.type === 'h5-wechat')
  const isDevelopment = computed(() => systemConfig.value.enableDebug)

  // 初始化应用
  const initApp = async () => {
    try {
      // 检查网络
      const networkStatus = await checkNetwork()
      if (!networkStatus) {
        console.warn('网络连接失败')
      }

      // 获取设备信息
      const deviceInfo = uni.getDeviceInfo()
      platformInfo.value.device = deviceInfo
      platformInfo.value.os = deviceInfo.platform?.toLowerCase() || 'unknown'

      // 获取浏览器信息
      platformInfo.value.browser = getBrowserInfo()

      // 获取微信信息
      platformInfo.value.wechat = {
        isWechatBrowser: isWechatBrowser(),
        isWechatMiniProgram: isWechatMiniProgram(),
        isWechatEnvironment: isWechatEnvironment(),
        version: getWechatVersion(),
        canUseJSSDK: false, // 需要在微信JS-SDK加载后设置
      }

      // 检查微信JS-SDK
      if (platformInfo.value.wechat.isWechatBrowser) {
        // #ifdef H5
        platformInfo.value.wechat.canUseJSSDK = typeof window !== 'undefined' && 'wx' in window
        // #endif
      }

      // 更新屏幕信息
      screenInfo.value = getScreenInfo()

      // 设置调试模式
      systemConfig.value.enableDebug = true // 临时设置，应该从环境变量读取

      // 标记为就绪
      platformInfo.value.isReady = true

      console.log('应用初始化完成', {
        platform: platformInfo.value.name,
        terminal: platformInfo.value.terminal,
        os: platformInfo.value.os,
        wechat: platformInfo.value.wechat,
        browser: platformInfo.value.browser,
        screen: screenInfo.value,
      })

      return true
    }
    catch (error) {
      console.error('应用初始化失败:', error)
      return false
    }
  }

  // 更新屏幕信息
  const updateScreenInfo = () => {
    screenInfo.value = getScreenInfo()
  }

  // 更新微信JS-SDK状态
  const updateWechatJSSDKStatus = (canUse: boolean) => {
    platformInfo.value.wechat.canUseJSSDK = canUse
  }

  // 设置主题
  const setTheme = (theme: string) => {
    systemConfig.value.theme = theme
  }

  // 设置语言
  const setLanguage = (language: string) => {
    systemConfig.value.language = language
  }

  // 显示全局加载
  function showGlobalLoading(text: string = '加载中...') {
    globalLoading.value = true
    loadingText.value = text
  }

  // 隐藏全局加载
  function hideGlobalLoading() {
    globalLoading.value = false
    loadingText.value = '加载中...'
  }

  // 显示Toast提示
  function showToast(message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info') {
    uni.showToast({
      title: message,
      icon: type === 'success' ? 'success' : type === 'error' ? 'error' : 'none',
      duration: 2000,
    })
  }

  // 显示成功提示
  function showSuccess(message: string) {
    showToast(message, 'success')
  }

  // 显示错误提示
  function showError(message: string) {
    showToast(message, 'error')
  }

  // 显示警告提示
  function showWarning(message: string) {
    showToast(message, 'warning')
  }

  // 显示确认对话框
  function showConfirm(options: {
    title?: string
    content: string
    confirmText?: string
    cancelText?: string
  }): Promise<boolean> {
    return new Promise((resolve) => {
      uni.showModal({
        title: options.title || '确认',
        content: options.content,
        confirmText: options.confirmText || '确定',
        cancelText: options.cancelText || '取消',
        success: (res) => {
          resolve(res.confirm)
        },
        fail: () => {
          resolve(false)
        },
      })
    })
  }

  // 显示操作菜单
  function showActionSheet(options: {
    title?: string
    itemList: string[]
    itemColor?: string
  }): Promise<number> {
    return new Promise((resolve, reject) => {
      uni.showActionSheet({
        title: options.title,
        itemList: options.itemList,
        itemColor: options.itemColor || '#000000',
        success: (res) => {
          resolve(res.tapIndex)
        },
        fail: () => {
          reject(new Error('用户取消操作'))
        },
      })
    })
  }

  return {
    // 应用信息
    appInfo,
    platformInfo,
    screenInfo,
    systemConfig,

    // 状态
    globalLoading,
    loadingText,

    // 计算属性
    isH5,
    isApp,
    isMiniProgram,
    isWechat,
    isWechatH5,
    isDevelopment,

    // 应用管理方法
    initApp,
    updateScreenInfo,
    updateWechatJSSDKStatus,
    setTheme,
    setLanguage,

    // UI方法
    showGlobalLoading,
    hideGlobalLoading,
    showToast,
    showSuccess,
    showError,
    showWarning,
    showConfirm,
    showActionSheet,
  }
})
